﻿using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using NLog;
using OfficeOpenXml;
using ClosedXML.Excel;

namespace Wittur.GenereateKongCoCPDF.Core.Common
{
    public class ExcelHepler
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();

        public static void ConvertExcelToPdf(string excelFilePath, string pdfFilePath)
        {
            Microsoft.Office.Interop.Excel.Application excelApp = null;
            Workbook workbook = null;

            try
            {
                // 创建 Excel 应用程序实例
                excelApp = new Microsoft.Office.Interop.Excel.Application();
                excelApp.Visible = false; // 不显示 Excel 界面

                // 打开 Excel 文件
                workbook = excelApp.Workbooks.Open(excelFilePath);
                logger.Info("打开文件正常");

                // 将 Excel 文件另存为 PDF
                workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, pdfFilePath);
                Console.WriteLine("转换成功！");
            }
            catch (Exception ex)
            {
                logger.Error($"转换失败: {ex.Message}");
                Console.WriteLine($"转换失败: {ex.Message}");
            }
            finally
            {
                // 关闭工作簿和 Excel 应用程序
                if (workbook != null)
                {
                    workbook.Close(false);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                }

                if (excelApp != null)
                {
                    excelApp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
                }
                if (File.Exists(excelFilePath))
                {
                    File.Delete(excelFilePath);
                }
            }
        }

        public static void ConvertExcelToPdfByEpp(string excelFilePath, string pdfFilePath)
        {
            using (var package = new ExcelPackage(new FileInfo(excelFilePath)))
            {
                var workbook = package.Workbook;
                var sheet = workbook.Worksheets[0];
                // 修改工作表内容
                package.SaveAs(new FileInfo(pdfFilePath));
            }
        }

        public static void ConvertExcelToPdfByClosedXML(string excelFilePath, string pdfFilePath)
        {
            using (var workbook = new XLWorkbook(excelFilePath))
            {
                var sheet = workbook.Worksheet(1);
                // 修改工作表内容
                workbook.SaveAs(pdfFilePath);
            }
        }
    }
}
